from app.extensions import get_db
from app.schames.Student import StudentSchema, StudentCreate
from app.services.StudentService import StudentService
from fastapi.responses import JSONResponse
from fastapi import APIRouter

student_router = APIRouter(prefix="/student", tags=["Student"])

def test():
    return {"modual": "student"}
@student_router.get("/", summary="搜索学生")
def get_by_keyword(keyword: str=""):
    with get_db() as db:
        svc = StudentService(db)
        response = svc.get_by_keyword(keyword)
        return JSONResponse(
            content={
                "data": [StudentSchema.model_validate(item).model_dump() for item in response["data"]],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )
@student_router.post("/", summary="添加学生")
def add_student(stu: StudentCreate):
    with get_db() as db:
        svc = StudentService(db)
        response = svc.add_student(stu.name,stu.gender,stu.clas_id)
        return JSONResponse(
            content={
                "data": response["data"],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )
@student_router.put("/{id}", summary="修改学生")
def modify_student(id: int, stu:StudentCreate):
    with get_db() as db:
        svc = StudentService(db)
        response = svc.modify_student(id, stu.name, stu.gender, stu.clas_id)
        return JSONResponse(
            content={
                "data": response["data"],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )
@student_router.delete("/{id}", summary="删除学生")
def delete_student(id: int):
    with get_db() as db:
        svc = StudentService(db)
        response = svc.delete_student(id)
        return JSONResponse(
            content={
                "data": response["data"],   # ORM转为dict
                "message": response["message"]
            },
            status_code=response["code"]
        )